<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import {
  Plus, // For 'Add Activity' button
  Edit, // For 'Edit' button
  CircleCloseFilled, // For 'Cancel' button
  Check, // For 'Update' / 'Create' button in dialog
  Close, // For 'Cancel' button in dialog
} from '@element-plus/icons-vue'

// --- Data Definitions ---
const activities = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEditMode = ref(false)

const activityFormRef = ref(null) // Reference to the form component for validation

const activityForm = reactive({
  activityId: null,
  activityName: '',
  activityDescription: '',
  activityDate: '',
  organizer: '',
  location: '',
  status: '', // Add status to form for potential display in edit mode
})

const formRules = reactive({
  activityName: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
  activityDate: [{ required: true, message: '请选择活动日期', trigger: 'change' }],
  organizer: [{ required: true, message: '请输入组织者', trigger: 'blur' }],
  location: [{ required: true, message: '请输入活动地点', trigger: 'blur' }],
})

// --- Methods ---

// Delay calling resetFields to avoid ResizeObserver warning
const handleDialogOpened = () => {
  setTimeout(() => {
    activityFormRef.value?.resetFields()
  }, 50)
}

// Fetches the list of patient education activities
const fetchActivities = async () => {
  try {
    const response = await axios.get('http://localhost:8080/education-activities')
    if (response.data.code === 200) {
      activities.value = response.data.data.map(activity => ({
        ...activity,
        updated: activity.updated || '', // Ensure 'updated' exists
        // Assign a tag type based on status for ElTag component
        statusType: getStatusTagType(activity.status)
      }))
      ElMessage.success('患教活动列表获取成功！')
    } else {
      ElMessage.error(`获取患教活动失败: ${response.data.msg || '未知错误'}`)
    }
  } catch (error) {
    console.error('获取患教活动时发生错误:', error)
    ElMessage.error('获取患教活动失败，请检查网络或服务器。')
  }
}

// Determines the ElTag type based on activity status
const getStatusTagType = (status) => {
  switch (status) {
    case '进行中':
      return 'success'
    case '已取消':
      return 'danger'
    case '已完成':
      return 'info'
    case '未开始':
    default:
      return 'warning'
  }
}

// Opens the dialog for adding a new activity
const openAddDialog = () => {
  isEditMode.value = false
  dialogTitle.value = '新增患教活动'
  // Reset form fields
  Object.assign(activityForm, {
    activityId: null,
    activityName: '',
    activityDescription: '',
    activityDate: '',
    organizer: '',
    location: '',
    status: '',
  })
  dialogVisible.value = true
}

// Opens the dialog for editing an existing activity
const openEditDialog = async (activityId) => {
  isEditMode.value = true
  dialogTitle.value = '编辑患教活动'
  try {
    const response = await axios.get(`http://localhost:8080/education-activities/${activityId}`)
    if (response.data.code === 200) {
      Object.assign(activityForm, {
        ...response.data.data,
        // Ensure activityDate is in correct format for picker if needed,
        // but value-format "YYYY-MM-DDTHH:mm:ss" handles ISO string directly
        activityDate: response.data.data.activityDate
      })
      dialogVisible.value = true
    } else {
      ElMessage.error(`获取活动详情失败: ${response.data.msg || '未知错误'}`)
    }
  } catch (error) {
    console.error('获取活动详情时发生错误:', error)
    ElMessage.error('获取活动详情失败，请检查网络或服务器。')
  }
}

// Submits the form for adding or updating an activity
const submitForm = async () => {
  try {
    await activityFormRef.value.validate() // Validate form fields

    let response
    if (isEditMode.value) {
      // For update, send all necessary fields including activityId
      response = await axios.put('http://localhost:8080/education-activities', activityForm)
    } else {
      // For create, exclude activityId
      // eslint-disable-next-line no-unused-vars
      const { activityId, ...createPayload } = activityForm
      response = await axios.post('http://localhost:8080/education-activities', createPayload)
    }

    if (response.data.code === 200) {
      ElMessage.success(`${isEditMode.value ? '更新' : '新增'}患教活动成功！`)
      dialogVisible.value = false // Close dialog
      fetchActivities() // Refresh list
    } else {
      ElMessage.error(`${isEditMode.value ? '更新' : '新增'}患教活动失败: ${response.data.msg || '未知错误'}`)
    }
  } catch (error) {
    console.error('提交表单时发生错误:', error)
    if (error.isAxiosError) {
      ElMessage.error('提交失败，请检查网络或服务器。')
    } else {
      ElMessage.error('表单校验失败，请检查输入项。')
    }
  }
}

// Cancels an activity after user confirmation
const cancelActivity = async (activityId) => {
  ElMessageBox.prompt('请输入取消原因', '取消患教活动', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /\S/, // Input must not be empty
    inputErrorMessage: '取消原因不能为空',
    type: 'warning', // Add warning icon to prompt
  }).then(async ({ value: cancelReason }) => {
    try {
      const response = await axios.post(
          `http://localhost:8080/education-activities/${activityId}/cancel?cancelReason=${encodeURIComponent(cancelReason)}`
      )
      if (response.data.code === 200) {
        ElMessage.success('患教活动已成功取消！')
        fetchActivities() // Refresh list to reflect status change
      } else {
        ElMessage.error(`取消患教活动失败: ${response.data.msg || '未知错误'}`)
      }
    } catch (error) {
      console.error('取消患教活动时发生错误:', error)
      ElMessage.error('取消患教活动失败，请检查网络或服务器。')
    }
  }).catch(() => {
    ElMessage.info('已取消操作。')
  })
}

// Formats the activity date for display
const formatActivityDate = (dateString) => {
  if (!dateString) return ''
  // If dateString is an ISO string, format it for display
  if (dateString.includes('T') && dateString.includes(':')) {
    // Example: "2023-10-26T10:00:00" -> "2023-10-26 10:00"
    return dateString.replace('T', ' ').substring(0, 16)
  }
  return dateString // Return as is if already formatted or different string
}

// Lifecycle hook
onMounted(() => {
  fetchActivities()
})
</script>

<template>
  <div class="education-activities-page">
    <el-card class="activities-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">患教活动管理</span>
          <el-button type="primary" :icon="Plus" @click="openAddDialog">新增活动</el-button>
        </div>
      </template>

      <el-table :data="activities" class="activities-table" border stripe>
        <el-table-column prop="activityName" label="活动名称" min-width="150" show-overflow-tooltip></el-table-column>
        <el-table-column prop="activityDescription" label="活动描述" min-width="200" show-overflow-tooltip></el-table-column>
        <el-table-column label="活动日期" width="170">
          <template #default="{ row }">
            {{ formatActivityDate(row.activityDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="organizer" label="组织者" width="120" show-overflow-tooltip></el-table-column>
        <el-table-column prop="location" label="地点" width="120" show-overflow-tooltip></el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.statusType" effect="light">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="{ row }">
            <el-button
                size="small"
                :icon="Edit"
                @click="openEditDialog(row.activityId)"
                class="table-action-button"
            >编辑</el-button>
            <el-button
                size="small"
                type="danger"
                :icon="CircleCloseFilled"
                @click="cancelActivity(row.activityId)"
                :disabled="row.status === '已取消' || row.status === '已完成'"
                class="table-action-button"
            >取消</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="600px"
        @close="activityFormRef?.resetFields()"
        @opened="handleDialogOpened"
        class="activity-dialog"
    >
      <el-form :model="activityForm" ref="activityFormRef" :rules="formRules" label-width="100px">
        <el-form-item label="活动名称" prop="activityName">
          <el-input v-model="activityForm.activityName" placeholder="请输入活动名称"></el-input>
        </el-form-item>
        <el-form-item label="活动描述">
          <el-input type="textarea" v-model="activityForm.activityDescription" :rows="3" placeholder="请输入活动详细描述"></el-input>
        </el-form-item>
        <el-form-item label="活动日期" prop="activityDate">
          <el-date-picker
              v-model="activityForm.activityDate"
              type="datetime"
              placeholder="选择活动日期和时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DDTHH:mm:ss"
              style="width: 100%;"
              popper-class="custom-date-picker-popper"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="组织者" prop="organizer">
          <el-input v-model="activityForm.organizer" placeholder="请输入组织者姓名或单位"></el-input>
        </el-form-item>
        <el-form-item label="活动地点" prop="location">
          <el-input v-model="activityForm.location" placeholder="请输入活动具体地点"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false" :icon="Close">取消</el-button>
          <el-button type="primary" @click="submitForm" :icon="isEditMode ? Check : Plus">
            {{ isEditMode ? '更新' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.education-activities-page {
  padding: 30px; /* Increased padding for overall page */
  background-color: #f8fbfd; /* Light background for the page */
  min-height: calc(100vh - 60px); /* Adjust to fit main layout */
}

.activities-card {
  border-radius: 12px; /* Softer rounded corners for the card */
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08); /* Subtle shadow for depth */
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5; /* Separator line */
  margin-bottom: 20px;
}

.card-title {
  font-size: 24px; /* Larger title font size */
  font-weight: bold;
  color: #333;
}

/* Table specific styles */
.activities-table {
  width: 100%;
  border-radius: 8px; /* Rounded corners for the table */
  overflow: hidden; /* Ensures corners are respected */
}

.activities-table :deep(.el-table__header-wrapper th) {
  background-color: #f2f6fc; /* Header background color */
  color: #555;
  font-weight: 600;
  padding: 12px 0; /* Adjust padding */
}

.activities-table :deep(.el-table__cell) {
  padding: 10px 0; /* Adjust cell padding */
}

.table-action-button {
  margin-right: 5px; /* Spacing between action buttons */
  border-radius: 4px;
}

/* ElTag for status */
.el-tag {
  font-size: 13px;
  height: 28px; /* Slightly taller tags */
  line-height: 26px;
  padding: 0 10px;
}

/* Dialog styles */
.activity-dialog :deep(.el-dialog__header) {
  padding: 20px 20px 10px;
  border-bottom: 1px solid #ebeef5;
}

.activity-dialog :deep(.el-dialog__title) {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.activity-dialog :deep(.el-dialog__body) {
  padding: 30px 40px; /* More padding inside dialog */
}

.activity-dialog .el-form-item {
  margin-bottom: 22px; /* Spacing between form items */
}

.activity-dialog .el-input,
.activity-dialog .el-textarea,
.activity-dialog .el-date-picker {
  width: 100%;
}

.dialog-footer .el-button {
  border-radius: 6px;
}

/* Custom popper for date picker (if needed for specific styling) */
.custom-date-picker-popper {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
</style>